<template>
  <div class="app-container bg">
    <div class="box-container">
      <div
        class="mb15"
        style="border-bottom: 1px solid #ddd; margin-bottom: 10px"
      >
        <el-radio-group
          v-model="showType"
          @change="showTypeChange"
          style="gap: 40px"
        >
          <el-radio-button label="1">科室</el-radio-button>
          <el-radio-button label="2">学员</el-radio-button>
        </el-radio-group>
      </div>

      <el-row
        :gutter="10"
        class="mb15 flex-container"
        style="
          font-size: 14px;
          line-height: 25px;
          margin-top: 20px;
          cursor: pointer;
          border-bottom: 1px solid #ddd;
        "
      >
        <el-col :span="2.5">
          <div
            @click="clickAll(0, null)"
            class="nactive"
            :class="{ active: tagIndex == 0 }"
          >
            全部：{{ registerBaseVo.total || 0 }}
          </div>
        </el-col>
        <el-col :span="2.5">
          <div
            @click="clickAll(1, 1)"
            class="nactive"
            :class="{ active: tagIndex == 1 }"
          >
            待分配：{{ registerBaseVo.allocationStatus1 || 0 }}
          </div>
        </el-col>
        <el-col :span="2.5">
          <div
            @click="clickAll(2, 2)"
            class="nactive"
            :class="{ active: tagIndex == 2 }"
          >
            已分配：{{ registerBaseVo.allocationStatus2 || 0 }}
          </div>
        </el-col>
      </el-row>

      <el-row v-if="showType == 2" :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            size="mini"
            :disabled="multiple"
            @click="allocationOpen(null)"
            >分配带教</el-button
          >
        </el-col>
      </el-row>
    </div>
    <el-form
      class="box-container"
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="" style="width: 160px" prop="registerDeptId">
        <el-select
          v-model="queryParams.registerDeptId"
          placeholder="请选择进修科目"
          filterable
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="(item, index) in registerDeptList"
            :key="index"
            :label="item.registerDeptName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label=""
        style="width: 160px"
        prop="registerTypeId"
        v-if="false"
      >
        <el-select
          v-model="queryParams.registerTypeId"
          placeholder="请选择招生类型"
          filterable
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="(item, index) in registerTypeList"
            :key="index"
            :label="item.registerTypeName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="" style="width: 160px" prop="batchName">
        <el-select
          v-model="queryParams.batchName"
          placeholder="请选择招生批次"
          filterable
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="(item, index) in registerBatchList"
            :key="index"
            :label="item.name"
            :value="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="" style="width: 160px" prop="registerYear">
        <el-date-picker
          v-model="queryParams.registerYear"
          type="year"
          placeholder="请选择招生年份"
          format="yyyy"
          style="width: 160px"
          value-format="yyyy"
          @change="handleQuery"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="" style="width: 160px" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <div class="box-container">
      <div v-if="showType == 1" class="custom-table">
        <div class="custom-dept" v-for="(row, index) in dataList" :key="index">
          <div class="colw title">{{ row.registerDeptName }}</div>
          <div class="colw flex">
            <div class="col">
              {{ row.total }}
              <div class="desc">录取总数</div>
            </div>

            <div class="col">
              <span class="red">{{ row.allocationStatus1 }}</span>
              <div class="desc">待分配</div>
            </div>
            <div class="col">
              {{ row.allocationStatus2 }}
              <div class="desc">已分配</div>
            </div>
          </div>

          <div class="colw func" @click="viewOpen(row)">
            <el-button size="small" type="primary">查看名单</el-button>
          </div>
        </div>
      </div>

      <div v-if="showType == 2" class="custom-table">
        <el-checkbox
          v-model="AllCheck"
          @change="handleSelectionChangeAll"
          style="transform: scale(1.2); margin-bottom: 20px; margin-left: 20px"
          >全选</el-checkbox
        >
        <div
          class="custom-register"
          v-for="(row, index) in dataList"
          :key="row.id"
        >
          <div class="border" style="display: flex; flex: 8">
            <div>
              <div class="user-name">
                <div style="margin-right: 10px">
                  <el-checkbox
                    v-model="row.check"
                    style="transform: scale(1.2)"
                    @change="handleSelectionChange($event, index)"
                  />
                </div>
                <span
                  style="
                    font-size: 18px;
                    font-weight: bolder;
                    color: #a52529;
                    cursor: pointer;
                  "
                  @click="detailOpen(row)"
                  >{{ row.userName }}</span
                >
                <el-tag
                  type="success"
                  v-if="row.allocationStatus == 2"
                  size="small"
                  style="margin-left: 10px"
                  >{{ row.allocationStatusName }}</el-tag
                >
                <el-tag
                  type="danger"
                  v-if="row.allocationStatus == 1"
                  size="small"
                  style="margin-left: 10px"
                  >{{ row.allocationStatusName }}</el-tag
                >

                <div style="margin-left: auto; font-size: 12px; color: #999">
                  工号：{{ row.jobNumber }}
                </div>
              </div>
              <div class="info">
                <div class="flexInfo">
                  <div>进修科目：{{ row.registerDeptName }}</div>
                  <div style="display: flex">
                    进修期限：
                    <span v-if="row.registerNoticeVo"
                      >{{ row.registerNoticeVo.startDate }} -
                      {{ row.registerNoticeVo.endDate }}</span
                    >
                    <div v-if="row.durationName">
                      （{{ row.durationName }}）
                    </div>
                  </div>
                  <div style="display: flex; align-items: center">
                    分配老师：
                    <div
                      v-for="(item, index) in row.registerAllocationVoList"
                      :key="index"
                      style="margin-right: 5px"
                    >
                      {{ item.teacherNickName }}
                    </div>
                  </div>
                </div>
                <div class="flexInfo">
                  <div>
                    报到时间：{{
                      row.registerNoticeVo &&
                      parseTime(row.registerNoticeVo.sureTime)
                    }}
                  </div>
                  <div>学习完成度：{{ row.progress }}%</div>

                  <div>申请单位：{{ row.unitHospitalName }}</div>
                </div>
              </div>
            </div>
          </div>

          <div
            class="border"
            style="
              width: 100%;
              display: flex;
              align-items: center;
              justify-content: center;
              position: relative;
            "
          >
            <i
              class="el-icon-delete systemColor"
              @click="handleDelete(row)"
              style="
                cursor: pointer;
                position: absolute;
                top: 10px;
                right: 10px;
                font-size: 20px;
              "
            ></i>
            <div
              style="display: flex; flex-direction: column; align-items: center"
            >
              <i class="el-icon-edit systemColor" style="font-size: 20px"></i>
              <el-button size="mini" type="text" @click="allocationOpen(row)"
                >分配带教
              </el-button>
            </div>
          </div>
        </div>
      </div>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <el-dialog
      title="报名详情"
      :visible.sync="detailShow"
      width="1040px"
      append-to-body
      :close-on-click-modal="false"
    >
      <registerInfoDetailInfo
        v-if="detailShow"
        :register-id="registerInfo.id"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailShow = false">关 闭</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="分配带教"
      :visible.sync="allocationShow"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="allocationForm"
        :model="allocationForm"
        :rules="allocationRules"
        label-width="80px"
      >
        <el-form-item label="带教老师" prop="teacherUserIdList">
          <el-select
            v-model="allocationForm.teacherUserIdList"
            multiple
            placeholder="请选择带教老师"
            filterable
            clearable
            remote
            reserve-keyword
            popper-class="teacherSelect"
            :remote-method="remoteMethod"
            :loading="remoteLoading"
          >
            <el-option
              v-for="(item, index) in remoteSysUserList"
              :key="index"
              :label="formatTeacherLabel(item)"
              :value="item.userId"
            >
              <el-tooltip
                effect="dark"
                :content="formatTeacherLabel(item)"
                placement="top"
              >
                <span>{{ formatTeacherLabel(item) }}</span>
              </el-tooltip>
            </el-option>
          </el-select>
          <div style="line-height: 25px; margin-top: 15px">
            分配提醒：如果删除已分配的带教老师，则对该学员的打分将会作废！
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="allocationSubmit">确 定</el-button>
        <el-button @click="allocationShow = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryByCountRegisterBase,
  queryByDeptRegisterBase,
  saveAllocationRegisterBase,
} from "@/api/business/registerBase";

import { setupBatchData } from "@/utils/batchUtils";

import { listAllRegisterDept } from "@/api/business/registerDept";
import { delRegisterInfo, listRegisterInfo } from "@/api/business/registerInfo";
import { listAllRegisterType } from "@/api/business/registerType";
import { listAllByRole } from "@/api/system/user";
import registerInfoDetailInfo from "../audit/components/registerInfoDetailInfo";

export default {
  name: "allocation",
  components: {
    registerInfoDetailInfo,
  },
  data() {
    return {
      // 根路径
      baseURL: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      detailShow: false, // 报到详情
      registerInfo: {
        id: null,
      },
      // 招生信息表格数据
      dataList: [],
      //全选
      AllCheck: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // 报到状态已报到
        sureStatus: 2,
        payNoRefund: 1,
        allocationStatus: null,
        registerDeptId: null,
        registerTypeId: null,
        batchName: null,
        registerYear: null,
        userName: null,
        isAllocationTeachModule: true,
      },
      registerDeptList: [],
      registerTypeList: [],
      batchDateList: [],
      registerBatchList: [],
      registerBaseVo: {},
      sysUserList: [],
      remoteSysUserList: [],
      remoteLoading: false,
      // 页面显示
      showType: 1,
      // 分配带教
      allocationShow: false,
      allocationForm: {},
      allocationRules: {
        teacherUserIdList: [
          { required: true, message: "带教老师不能为空", trigger: "blur" },
        ],
      },
      tagIndex: 0,
      detailShow: false, // 报到详情
    };
  },
  async created() {
    await this.getbatch();
    this.initData();
    this.listAllRegisterDept();
    this.listAllRegisterType();
    this.listAllUser();
  },
  methods: {
    // 获取批次数据
    async getbatch() {
      await setupBatchData(this);
    },
    detailOpen(row) {
      this.registerInfo.id = row.id;
      this.detailShow = true;
    },
    initData() {
      this.getCount();
      this.getList();
    },
    clickAll(index, value) {
      this.canselAllcheck();

      this.tagIndex = index;
      this.queryParams.allocationStatus = value;
      this.getList();
    },
    listAllRegisterDept() {
      listAllRegisterDept().then((response) => {
        this.registerDeptList = response.data;
      });
    },
    listAllRegisterType() {
      listAllRegisterType().then((response) => {
        this.registerTypeList = response.data;
      });
    },
    listAllUser() {
      // listAllUser().then((response) => {
      //   this.sysUserList = response.data;
      // });
      listAllByRole(4).then((response) => {
        this.sysUserList = response.data;
        this.remoteSysUserList = response.data;
      });
    },

    formatTeacherLabel(item) {
      return (
        item.userName +
        " " +
        item.nickName +
        (item.registerDeptNameList ? " " + item.registerDeptNameList : "")
      );
    },
    // 远程搜索
    remoteMethod(query) {
      if (query !== "") {
        this.remoteLoading = true;
        this.remoteSysUserList = this.sysUserList.filter((item) => {
          return (
            item.userName.toLowerCase().indexOf(query.toLowerCase()) > -1 ||
            item.nickName.toLowerCase().indexOf(query.toLowerCase()) > -1 ||
            this.allocationForm.teacherUserIdList.indexOf(item.userId) > -1
          );
        });
        console.log(this.remoteSysUserList);
        this.remoteLoading = false;
      } else {
        this.remoteSysUserList = [];
      }
    },
    getCount() {
      queryByCountRegisterBase(this.queryParams).then((response) => {
        if (response.data) {
          this.registerBaseVo = response.data;
          this.registerBaseVo.total =
            this.registerBaseVo.allocationStatus1 +
            this.registerBaseVo.allocationStatus2;
        }
      });
    },
    getList() {
      this.loading = true;
      if (this.showType == 1) {
        queryByDeptRegisterBase(this.queryParams).then((response) => {
          this.dataList = response.rows;
          for (let i = 0; i < this.dataList.length; i++) {
            this.dataList[i].total =
              this.dataList[i].allocationStatus1 +
              this.dataList[i].allocationStatus2;
          }
          this.total = response.total;
          this.loading = false;
        });
      } else if (this.showType == 2) {
        listRegisterInfo(this.queryParams).then((response) => {
          this.dataList = response.rows;
          this.dataList.forEach((row) => {
            this.$set(row, "check", false);
          });
          this.total = response.total;
          this.loading = false;
        });
      }
    },
    // 分配带教
    allocationOpen(row) {
      if (row) {
        let allocationList = row.registerAllocationVoList;
        let teacherUserIdList = [];
        if (allocationList && allocationList.length > 0) {
          for (let i = 0; i < allocationList.length; i++) {
            teacherUserIdList.push(allocationList[i].teacherUserId);
          }
        }
        this.allocationForm = {
          registerIdList: [row.id],
          teacherUserIdList: teacherUserIdList,
        };
        console.log(teacherUserIdList);
        this.remoteSysUserList = this.sysUserList.filter((item) => {
          return teacherUserIdList.indexOf(item.userId) > -1;
        });
      } else {
        let list = this.dataList.filter((e) => this.ids.indexOf(e.id) > -1);
        for (let i = 0; i < list.length; i++) {
          if (list[i].allocationStatus != 1) {
            this.$modal.msgError("请选择分配状态为待分配的学员");
            return;
          }
        }
        this.allocationForm = {
          registerIdList: this.ids,
          teacherUserIdList: [],
        };
      }
      this.allocationShow = true;
    },
    allocationSubmit() {
      this.$refs["allocationForm"].validate((valid) => {
        if (valid) {
          saveAllocationRegisterBase(this.allocationForm).then((response) => {
            this.$modal.msgSuccess("分配成功");
            this.initData();
            this.allocationShow = false;
          });
        } else {
          this.$modal.msgError("请完善表单内容");
        }
      });
    },
    // 查看名单
    viewOpen(row) {
      this.showType = 2;
      this.queryParams.registerDeptId = row.registerDeptId;
      this.handleQuery();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除报名信息编号为"' + ids + '"的数据项？')
        .then(function () {
          return delRegisterInfo(ids);
        })
        .then(() => {
          this.initData();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 切换视图
    showTypeChange() {
      this.canselAllcheck();
      this.ids = [];
      this.single = true;
      this.multiple = true;
      this.queryParams.registerDeptId = null;
      this.queryParams.userName = null;
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.canselAllcheck();

      this.queryParams.pageNum = 1;
      this.initData();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.canselAllcheck();

      this.resetForm("queryForm");
      // 手动重置批次和年份为空
      this.queryParams.batchName = null;
      this.queryParams.registerYear = null;
      this.handleQuery();
    },
    //取消全选
    canselAllcheck() {
      this.dataList.forEach((item) => {
        if (item.check) {
          this.$set(item, "check", false);
        }
      });
      this.AllCheck = false;
      this.ids = [];
      this.single = true;
      this.multiple = true;
    },
    handleSelectionChangeAll(checked) {
      let ids = [];
      for (let i = 0; i < this.dataList.length; i++) {
        // 使用 $set 确保属性被响应式地修改
        this.$set(this.dataList, i, { ...this.dataList[i], check: checked });
        if (checked) {
          ids.push(this.dataList[i].id);
        }
      }
      this.ids = ids;
      this.single = ids.length !== 1;
      this.multiple = !ids.length;
      console.log(this.multiple);
      console.log(this.single);
    },
    // 多选框选中数据
    // handleSelectionChange(selection) {
    //   this.ids = selection.map((item) => item.id);
    //   this.single = selection.length !== 1;
    //   this.multiple = !selection.length;
    // },
    handleSelectionChange(checked, index) {
      console.log(checked, index);
      // 使用 $set 确保属性被响应式地修改
      this.$set(this.dataList, index, {
        ...this.dataList[index],
        check: checked,
      });

      let ids = [];
      for (let i = 0; i < this.dataList.length; i++) {
        if (this.dataList[i].check) {
          ids.push(this.dataList[i].id);
        }
      }
      this.ids = ids;
      this.single = ids.length !== 1;
      this.multiple = !ids.length;
    },
  },
};
</script>
<style lang="scss">
::v-deep .el-dialog__body {
  padding: 0 20px 20px 20px;
}

::v-deep .el-select {
  max-width: 100%;
}

::v-deep .el-select-dropdown {
  max-width: 100%;
  min-width: 300px;
  z-index: 9999 !important;
}

::v-deep .el-select-dropdown__item {
  white-space: normal;
  word-break: break-word;
  padding: 8px 20px;
  max-width: 400px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.user-name {
  display: flex;
  align-items: center;
}

.box-container {
  padding: 0;
  padding-left: 20px;
}

.flex-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  /* 控制列之间的间距 */
  background: #eeeff4;
  padding: 20px 0;
}

::v-deep .el-radio-button__orig-radio + .el-radio-button__inner {
  width: 140px;
}

::v-deep .el-radio-button__orig-radio:checked + .el-radio-button__inner {
  width: 140px;
}

.custom-table {
  .custom-dept {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border: 1px solid #d8d8d8;
    padding: 0 20px;
    height: 90px;
    margin-bottom: 20px;
    text-align: center;
    font-size: 18px;
    font-weight: bold;

    .col {
      width: calc(100% / 3);
      // font-weight: bolder;

      .desc {
        font-size: 12px;
        color: #888;
        margin-top: 10px;
        font-weight: normal;
      }
    }
  }

  .custom-dept:hover {
    border: 1px solid red;
  }

  .custom-register {
    display: flex;
    justify-content: space-between;
    align-items: center;
    // border: 1px solid rgb(232, 232, 232);
    // padding: 10px;
    // text-align: center;
    font-size: 14px;
    margin-bottom: 10px;
    height: 150px;

    .info {
      display: flex;
      justify-content: space-between;
      color: #606266;
      font-size: 14px;

      .flexInfo {
        display: flex;
        flex-direction: column;
        margin-top: 10px;
        font-size: 14px;
        width: 450px;
        line-height: 20px;
        flex: 1;
      }
    }

    .col {
      .desc {
        color: #666666;
        margin-top: 10px;
        font-weight: normal;
      }
    }

    .col:nth-child(1) {
      width: calc(100% - 600px);
      text-align: left;
    }

    .col:nth-child(2) {
      width: 200px;
    }

    .col:nth-child(3) {
      width: 200px;
    }

    .col:nth-child(4) {
      width: 200px;
    }

    .col:nth-child(5) {
      width: 200px;
    }
  }
}
.teacherSelect {
  width: 300px;
}
</style>
